package com.linshengjian.snowball.core;

import com.linshengjian.snowball.core.exception.DataHandlerException;
import com.linshengjian.snowball.core.exception.DataManagerException;

import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class DataWrapper {

    private Class type;

    private IDataHandler handler;

    private Set<IDataEvent> events = new HashSet<>();

    private Map<Class, DataWrapper> outreach = new HashMap<>(); // 外联哪些数据

    private Map<Class, DataWrapper> use = new HashMap<>(); // 使用到这个数据的

    public DataWrapper(Class type, IDataHandler handler) {
        this.type = type;
        this.handler = handler;
    }

//    private Class getType() {
//        return this.type;
//    }

    IDataHandler getHandler() {
        return this.handler;
    }

    Set<IDataEvent> getEvents() {
        return events;
    }

    public void addEvent(IDataEvent event) {
        events.add(event);
    }

    public void addUse(DataWrapper wrapper) {
        wrapper.outreach.put(wrapper.type, this);
        use.put(wrapper.type, wrapper);
    }

    DataWrapper getUse(Class type) {
        return use.get(type);
    }

    public DataWrapper getOutreach(Class type) {
        return outreach.get(type);
    }

    /**
     * 获取数据
     * @param unique 唯一值
     * @return
     */
    public DataExecutor get(Serializable unique) throws DataHandlerException {
        Object data = handler.get(unique);
        return getInstance(data);
    }

    /**
     * 根据数据实例化
     * @param data
     * @return
     * @throws DataManagerException
     */
    public DataExecutor getInstance(Object data) throws DataHandlerException {
        if (!data.getClass().equals(type))
            throw new DataHandlerException(data.getClass().getName() + " 不是 " + type.getName());

        DataExecutor executor = new DataExecutor(this, data, handler, this.events);
        return executor;
    }
}
